<template>
  <div class="settings-container">
    <el-card class="settings-card" shadow="hover">
      <h2 class="card-title">设置中心</h2>
      <div class="section">
        <h3>基本信息</h3>
        <el-form label-width="100px" label-position="left">
          <el-form-item label="名称">
            <el-input v-model="user.nickname" placeholder="请输入昵称" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="user.email" placeholder="请输入邮箱" />
          </el-form-item>
        </el-form>
      </div>

      <hr class="divider" />

      <div class="section">
        <h3>修改密码</h3>
        <el-form label-position="left" label-width="100px" @submit.prevent="submitForm">
          <el-form-item label="新密码">
            <el-input v-model="user.password" type="password" />
          </el-form-item>
          <el-button type="warning" native-type="submit" icon="lock">更改信息</el-button>
        </el-form>
      </div>


      <hr class="divider" />

      <!-- 外观设置 -->
      <div class="section">
        <h3>外观与语言</h3>
        <div class="option-row">
          <span>主题模式：</span>
          <el-switch
              v-model="darkMode"
              active-text="暗色"
              inactive-text="亮色"
              @change="toggleTheme"
          />
        </div>
      </div>

      <hr class="divider" />

      <!-- 通知设置 -->
      <div class="section">
        <h3>通知与数据</h3>
        <div class="option-row">
          <span>接收通知：</span>
          <el-switch v-model="notifications" />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getUserInfo, updateuser } from "@/api/auth.js";

export default {
  data() {
    return {
      user: {
        id: '',
        password: '',
        nickname: '',
        status: true,
        email: ''
      },
      darkMode: false,
      language: 'zh',
      notifications: true,
    };
  },
  mounted() {
    this.fetchUser();
  },
  methods: {
    fetchUser() {
      getUserInfo()
          .then(res => {
            if (res.data) {
              this.user = res.data;
            } else {
              this.$message.error('无法获取用户数据');
            }
          })
          .catch(() => {
            this.$message.error('获取用户信息失败');
          });
    },
    submitForm() {
      if (!this.user.nickname || !this.user.email) {
        this.$message.warning('昵称和邮箱不能为空');
        return;
      }

      updateuser(this.user)
          .then(res => {
            if (res.data != null) {
              this.$message.success('用户信息更新成功');
              this.$router.push('/');
            } else {
              this.$message.error('更新用户信息失败');
            }
          })
          .catch(() => {
            this.$message.error('更新用户信息失败');
          });
    },
    toggleTheme() {
      this.darkMode = !this.darkMode;
    }
  }
};
</script>

